package cn.edu.njust.Filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*
 *登录过滤器，用于过滤未登录用户
 */

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        String[] urls = {"/login.jsp","/index.jsp","/LoginController","/kaptcha","/loginFailure.jsp","/help.html","/ForgetPassword.jsp"};
        // 获取当前访问的资源路径
        String url = req.getRequestURI();
//        System.out.println(url);
        String url1 = req.getContextPath();
//        System.out.println(url1);
        if(url.equals(url1+"/")){//特判默认页，直接放行
            chain.doFilter(request, response);
            return;
        }
        //循环判断
        for (String u : urls) {
            if(url.contains(u)){
                chain.doFilter(request, response);
                return;
            }
        }
        Object user = session.getAttribute("user");
        if (user != null){          //用户已登录，放行
            chain.doFilter(request, response);
        }else{                      //未登录，拦截并弹出提示信息
            req.setAttribute("login_msg","请先登录！");
            req.getRequestDispatcher("/login.jsp").forward(req,response);
        }

    }

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }
}
